package com.zjp.blog.controller.manage;

import com.zjp.blog.base.ApplicationContext;
import com.zjp.blog.controller.BaseController;
import com.zjp.blog.data.model.Config;
import com.zjp.blog.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */

@Controller
@RequestMapping("/manage/config")
public class ConfigController extends BaseController{
    private static String CREATE_OR_UPDATE  = "/manage/admin/create_or_update";

    @Autowired
    ConfigService configService;

    @Autowired
    ApplicationContext appContext;

    @RequestMapping
    public String list(ModelMap map){
        map.addAttribute("configs",appContext.getSystemConfigs());
        return null;
    }

    @RequestMapping(value = "update",method = RequestMethod.GET)
    public String update(Integer id ,ModelMap map){

        Config config = configService.getById(id);
        map.addAttribute("config",config);

        return CREATE_OR_UPDATE;
    }


    @RequestMapping(value = "update",method = RequestMethod.POST)
    public String update(Config config,RedirectAttributes redirectAttributes){
        configService.updateById(config);
        appContext.getSystemConfigs().put(config.getKey(),config);
        addMessage(redirectAttributes,"Update Success");
        return "redirect:" + "/manage";
    }

    @RequestMapping(value = "refresh",method = RequestMethod.POST)
    public String refresh(RedirectAttributes redirectAttributes){

        try {
            List<Config> list = configService.listAll();
            appContext.setSystemConfigs(list);
            addMessage(redirectAttributes, "refresh Success");
        }catch (Exception e){
            addError(redirectAttributes,"refresh failed");
        }
        return "redirect:" + "/manage";
    }

}
